/*
 * Part of knowledge engineering (ke) course work, 2010/11
 */
package se.bth.ke.firstfriend.web;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.springframework.stereotype.Component;
import de.nixis.commons.web.base.Controller;
import org.springframework.transaction.annotation.Transactional;
import se.bth.ke.firstfriend.model.Topic;
import se.bth.ke.firstfriend.dto.ArticlesByTopic;
import se.bth.ke.firstfriend.model.dto.TopicInfo;

/**
 *
 * @author nico.rehwaldt
 */
@Component
@Path("/topic")
public class TopicController extends Controller {
    
    @PersistenceContext
    private EntityManager em;

    @GET
    @Path("/{id:[\\d]+}-{slug}")
    @Transactional
    public ArticlesByTopic show(
            @PathParam("id") long id,
            @PathParam("slug") String slug) {

        Topic t = (Topic) em.createQuery("SELECT t FROM Topic t LEFT JOIN FETCH t.articles WHERE t.id = :id")
                            .setParameter("id", id)
                            .getSingleResult();

        return new ArticlesByTopic(t, t.getArticles());
    }

    @Transactional
    public List<TopicInfo> getTopicInfos() {
        List<TopicInfo> result = (List<TopicInfo>) em.createQuery("SELECT new se.bth.ke.firstfriend.model.dto.TopicInfo(t, COUNT(a)) FROM Topic t JOIN t.articles a GROUP BY t.id")
                                                     .getResultList();

        return result;
    }
}
